from functools import cache
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
from apps.address.models import Address
from apps.address.services import AddressService
from django.db import transaction
from rest_framework.views import APIView
from rest_framework.response import Response
from django.shortcuts import get_object_or_404
from django.db import transaction
from django.core.cache import cache
from apps.address.models import Address

class AddressViewSet(viewsets.ModelViewSet):
    @action(detail=False, methods=['GET'])
    def city_addresses(self, request):
        """获取同城地址列表（替代原nearby_cooks）"""
        city = request.query_params.get('city')
        if not city:
            return Response({"error": "参数city必填"}, status=400)
        
        queryset = AddressService.get_nearby(city)
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

class AddressSetDefaultAPI(APIView):
    def patch(self, request, pk):
        with transaction.atomic():
            Address.objects.filter(user=request.user).update(is_default=False)
            address = get_object_or_404(Address, pk=pk, user=request.user)
            address.is_default = True
            address.save()
            cache.delete(f'user_{request.user.id}_default_address')
        return Response(status=204)

class AddressDeleteCheckAPI(APIView):
    """删除前检查（需订单模块配合）"""
    def get(self, request, pk):
        from apps.orders.models import Order  # 需要订单模型
        used = Order.objects.filter(address_id=pk).exists()
        return Response({
            'can_delete': not used,
            'reason': '地址已被订单关联' if used else None
        })